<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8" />
	<title>分析页面form表单</title>
	<style type="text/css">
		body{margin:0;padding:0;font-size:14px;font-family:Tahoma,SimSun; height:100%}
		div {display: block;margin:0 auto}
		p{margin:0 auto;padding:0;}
		
		.container{width:1318px;}
		.analysis{width:950px;margin:0 auto;border:1px solid #969696;}
		
		.page_head{width:1318px;height: 30px}
		.page_left{width:363px;float:left;border:1px solid #969696;}
		.page_right{width:950px;float:right;border:1px solid #969696;}
		
		.project_name,.project_list{width:350px;float:left;margin-left: 3px;}
		.project_delete_link{width:30px;float:right;}
		.project_add_link{width:80px;float:right;}
		
		.project_name_edit,.project_name_add{width:265px;}
		.project_update_bt,.project_cancle_update_bt,.project_cancle_add_bt,.project_add_bt{width:38px;}
		.project_edit,.function_edit,.project_add,.function_add{display:none;}

		.function_name {width:327px;margin-left: 25px;}
		.function_delete{width:32px;float:right;}
		
		.function_name_edit,.function_name_add {width:245px;}
		.function_update_bt,.function_cancle_update_bt,.function_add_bt,.function_cancle_add_bt{width:38px;}
		.function_edit,.function_add{margin-left: 20px;}
		.function_add_link{width:50px;float:right;}
	</style>
</head>
<body>
	<div class="container">
		<div class="page_head">
		
		</div>
		<div class="page_left">
			<p>项目列表<a class="project_add_link" onclick="showAddProject()">新加项目</a></p>
			<div class="project_list">
			</div>
		</div>
		
		<div class="page_right">
			<div class="analysis">
				地址：<input type="text" id="url" style="width: 300px"/><a href="#" id='parseUrl'>分析</a>
			</div>
			
			<div id="parseForm" action="">
			</div>
		</div>
	</div>
	<script type="text/javascript" src="/js/jquery.min.js"></script>
	<script type="text/javascript">
		String.prototype.format = function(O){
			var s = this.replace(/\@\{(\w+)\}/g, function(t, _o){
				return O[_o]==null?'':O[_o];
			});
			return s;
		};
		
		var formTemplate = ['<p>表单名: @{formName}  ',
		                    '提交地址: <input id="action_@{i}" value="@{formAction}" style="width:300px"/>',
		                    'method:<input id="method_@{i}" value="@{method}" style="width:30px"/> </p>'].join('');
		var inputTemplate = [
						'<input id="@{fIdx}_eleName_@{i}" type="text" name="@{fIdx}_eleName_@{i}" value="@{name}"/>',
						'<input id="@{fIdx}_eleValue_@{i}" type="text" name="@{fIdx}_eleValue_@{i}" value="@{value}"/>',
						'<input id="@{fIdx}_eleType_@{i}" type="text" name="@{fIdx}_eleType_@{i}" value="@{type}"/>',
						'<input id="@{fIdx}_delete_@{i}" type="button" value="删除" onclick="del(@{fIdx},@{i})"/><br/>'
						].join('');
		
		var buttonTemplate = [
		                      '<input id="save_@{i}" type="button" value="保存"/>',
		                      '<input id="test_@{i}" type="button" value="测试" onclick="test(@{i})"/>'
		                      ].join(''); 
		
		
		function del(fIdx,i){
			$("#"+fIdx+"_eleName_"+i).remove();
			$("#"+fIdx+"_eleValue_"+i).remove();
			$("#"+fIdx+"_eleType_"+i).remove();
			$("#"+fIdx+"_delete_"+i).next().remove();
			$("#"+fIdx+"_delete_"+i).remove();
		}
		
		
		function getActionWithHost(action,url){
			var actionUrl = action;
			if(action.toLowerCase().indexOf('http') !=0){
				host = url.split('/')[2];
				actionUrl = 'http://'+host+action;
			}
			
			return actionUrl
		}
		
		function pushForm(forms){
			$.each(forms,function(i){
				$("#parseForm").append(formTemplate.format({
												i:i,
												formName:forms[i].formName,
												formAction:getActionWithHost(forms[i].formAction,$("#url").val()),
												method:forms[i].method})
									   );
				
				var inputs = forms[i].inputs;
				$.each(inputs,function(j){
					$("#parseForm").append(inputTemplate.format({
						i:j,
						fIdx:i,
						name:inputs[j].name,
						value:inputs[j].value,
						type:inputs[j].type
					}));
				});
				
				$("#parseForm").append(buttonTemplate.format({
					i:i})
		   		);
			});
		}
		
		function parse(){
			var url = "/parse/form?url="+$("#url").val();
			$.getJSON(url,function(data){
				$("#parseForm").html('');
				if(data.code == 1){
					var forms = data.data.parse.formList;
					if(forms.length == 0){
						$("#parseForm").append("页面没有找到表单");
					} else {
						pushForm(forms);
					}
				} else {
					$("#parseForm").append(data.msg);
				}
			});	
		}
		
		function formData(fIdx){
			var eleNm = fIdx+"_eleName_";
			var eleVal = fIdx+"_eleName_";
			
			var args = new Object();
			$('input[id^='+eleNm+']').each(function(){
				idx = $(this).attr("id").split('_')[2];
				var key = $("#"+eleNm+idx).val();
				var value = $("#"+eleVal+idx).val()
				
				args[key]=value;
			});
			
			return JSON.stringify(args);
		}
		
		function test(i){
			var testAction = $.ajax({
				url : "/parse/test",
				type : "post",
				async : false,
				data : {
					formData:formData(i),
					url:$("#action_"+i).val(),
					method:$("#method_"+i).val()
				},
				dataType : "json"
			});
			testAction.done(function(data) {
				NewWindow = window.open("","_blank");
				NewWindow.document.write(data.data.content);
			});
		}
		
		var projectTemplate = [
								'<div class="project_name" pid=@{id} >',
									'<a class="project_delete_link" pid=@{id} onclick="deleteProject($(this))">删除</a>',
									'<a class="function_add_link" onclick="showAddFunction($(this),@{id})">新加</a>',
									'<p>@{name}</p>',
								'</div>' 
							   ].join('');
		var editProjectTemplate = [
		                           '<div class="project_edit">',
										'<input type="text" class="project_name_edit" value="@{value}"/>',
										'<input type="button" pid=@{pid} class="project_update_bt" value="更新"/>',
										'<input type="button" class="project_cancle_update_bt" value="取消"/>',
									'</div>'
		                           ].join('');
		var addProjectTemplate = [
									'<div class="project_add">',
										'<input type="text" class="project_name_add" id="newProject"/>',
										'<input type="button" class="project_add_bt" onclick="addProject()" value="添加"/>',
										'<input type="button" class="project_cancle_add_bt" onclick="cancelAddProj()" value="取消"/>',
									'</div>'
		                          ].join('');
		

		function loadProject(){
			var url = "/project/query";
			var projects = $.ajax({
				url : url,
				type : "get",
				async:false,
				dataType : "json"
			});
			
			projects.done(function(data){
				if(data.code == 1){
					var projects = data.data.projects
					$(".project_list").append(addProjectTemplate);
					$.each(projects,function(i){
						$(".project_list").append(projectTemplate.format({name:projects[i].name,id:projects[i].id}));
						$(".project_list").append(editProjectTemplate.format({
							value:projects[i].name,
							pid:projects[i].id
						}))
					});
					
					addProjectEvent();
				}
			});
		}
		//定义setTimeout执行方法
		var TimeFn = null;
		function addProjectEvent(){
			$("div.project_name >p").dblclick(function(){
				clearTimeout(TimeFn);
				//编辑项目
				$(this).parent().hide();
				$(this).parent().next().show();
				
				$(".project_update_bt").click(function(){
					var pid = $(this).attr("pid");
					var pNm = $(this).prev().val();
					updateProject($(this),pid,pNm);
				});
				
				$(".project_cancle_update_bt").click(function(){
					$(this).parent().hide();
					$(this).parent().prev().show();
				});
			});
			
			//添加显示隐藏模块事件
			$("div.project_name >p").die().live("click",function(){
				var p = $(this);
				// 取消上次延时未执行的方法
			    clearTimeout(TimeFn);
			    //执行延时
			    TimeFn = setTimeout(function(){
					var obj = p.parent().children(".function_name");
					var addBt = p.parent().children(".function_add_link");
					var funcAdd = p.parent().children(".function_add");
					var funcEdit = p.parent().children(".function_edit");
					if(obj.length==0){
						loadFunctions(p.parent(),p.parent().attr("pid"));
					} else if(obj.length>0 && obj.is(":hidden")){
						obj.show();
						cancleAllEditFunc(funcEdit);
					} else {
						cancleAllEditFunc(funcEdit);
						obj.hide();
						addBt.show();
					}
			    },300);
			});
		}
		
		function cancleAllEditFunc(funcEdits){
			$.each(funcEdits,function(i){
				$(funcEdits[i]).hide();
			});
		}

		function showAddProject(){
			$(".project_add").show();
		}
		
		function addProject(){
			var pNm = $("#newProject").val();
			if(!!!pNm){
				alert('项目名称不可以为空！');
				return;
			}
			
			var url = "/project/create/"+pNm;
			var addProj = $.ajax({
				url : url,
				type : "get",
				async:false,
				dataType : "json"
			});
			
			addProj.done(function(data){
				if(data.code == 1){
					var project = data.data.projects[0];
					$(".project_list").append(projectTemplate.format({name:project.name,id:project.id}));
					$(".project_list").append(editProjectTemplate.format({
						value:project.name,
						pid:project.id
					}));
					$("#newProject").val('');
					
					addProjectEvent();
				}
			});
		}
		
		function cancelAddProj(){
			$(".project_add").hide();
		}
		
		function updateProject(obj,pid,pNm){
			var url = "/project/update/"+pid+"/"+pNm;
			var updatePrj = $.ajax({
				url : url,
				type : "get",
				async:false,
				dataType : "json"
			});
			
			updatePrj.done(function(data){
				if(data.code == 1){
					obj.parent().prev().children("p").html(pNm);
					obj.parent().hide();
					obj.parent().prev().show();
				}
			});
		}
		
		function deleteProject(obj){
			if(!confirm("确定删除!")){
				return;
			}
			
			var delProject = $.ajax({
				url : "/project/delete/"+obj.attr("pid"),
				type : "POST",
				async:false,
				dataType : "json"
			});
			
			delProject.done(function(data){
				if(data.code == 1){
					obj.parent().remove();
				}else{
					alert(data.msg);
				}
			});
		}
		
		
		
		var funcTemplate = [
		                    '<div class="function_name" fid="@{fid}">',
		                    	'<a class="function_delete" fid="@{fid}" onclick="deleteFunc($(this))">删除</a>',
		                    	'<p>@{fname}</p>',
		                    '</div>'
		                    ].join('');
		var editFuncTemplate = ['<div class="function_edit">',
									'<input type="text" class="function_name_edit" value="@{value}"/>',
									'<input type="button" fid=@{fid} class="function_update_bt" value="更新"/>',
									'<input type="button" class="function_cancle_update_bt" value="取消"/>',
								'</div>'
		                           ].join('');
		var addFuncTemplate = [
								'<div class="function_add">',
									'<input type="text" class="function_name_add" id="newFunction"/>',
									'<input type="button" class="function_add_bt" onclick="addFunction($(this))" value="添加"/>',
									'<input type="button" class="function_cancle_add_bt" value="取消"/>',
								'</div>'
		                       ].join('');
		//obj -> project_name
		function loadFunctions(obj,pid){
			var url = "/func/query/"+pid;
			var func = $.ajax({
				url : url,
				type : "get",
				async:false,
				dataType : "json"
			});
			
			func.done(function(data){
				if(data.code == 1){
					var funcs = data.data.functions;
					var funcAdd = obj.children(".function_add");
					if(!funcAdd[0]) obj.append(addFuncTemplate);
					$.each(funcs,function(i){
						obj.append(funcTemplate.format({fname:funcs[i].name,fid:funcs[i].id}));
						obj.append(editFuncTemplate.format({
							value:funcs[i].name,
							fid:funcs[i].id
						}));
					});
					
					addFuncEvent();
				}
			});
		}
		
		function addFuncEvent(){
			$("div.function_name >p").dblclick(function(){
				//编辑项目
				$(this).parent().hide();
				$(this).parent().next().show();
				
				$(".function_cancle_update_bt").click(function(){
					$(this).parent().hide();
					$(this).parent().prev().show();
				});
				
				$(".function_update_bt").click(function(){
					var fid = $(this).attr("fid");
					var fNm = $(this).prev().val();
					updateFunction($(this),fid,fNm);
				});
			});
			
			
			$(".function_cancle_add_bt").click(function(){
				$(this).parent().hide();
				$(this).parent().parent().children(".function_add_link").show();
			});
			
			/**
			$(".function_add_bt").click(function(){
				var pid = $(this).parent().parent().attr("pid");
				var fNm = $(this).parent().children("#newFunction").val();
				addFunction($(this),pid,fNm);
			});
			*/
		}
		
		function updateFunction(obj,fid,fNm){
			var url = "/func/update/"+fid+"/"+fNm;
			var updateFunc = $.ajax({
				url : url,
				type : "get",
				async:false,
				dataType : "json"
			});
			
			updateFunc.done(function(data){
				if(data.code == 1){
					obj.parent().prev().children("p").html(fNm);
					obj.parent().hide();
					obj.parent().prev().show();
				}
			});
		}
		
		function showAddFunction(obj,pid){
			obj.hide();
			
			var fNms = obj.parent().children(".function_name");
			if(fNms.length == 0){
				loadFunctions(obj.parent(),pid);
			}
			
			var fAdd = obj.parent().children(".function_add");
			if(fAdd.is(":hidden")){
				fAdd.show();
			}
		}
		
		function addFunction(obj){
			var pid = obj.parent().parent().attr("pid");
			var fNm = obj.parent().children("#newFunction").val();
			
			if(!fNm){
				alert('模块名称不可以为空！');
				return;
			}
			
			var url = "/func/create/"+pid+"/"+fNm;
			var addFunc = $.ajax({
				url : url,
				type : "get",
				async:false,
				dataType : "json"
			});
			
			addFunc.done(function(data){
				if(data.code == 1){
					var func = data.data.functions[0];
					obj.parent().parent().append(funcTemplate.format({fname:func.name,fid:func.id}));
					obj.parent().parent().append(editFuncTemplate.format({
						value:func.name,
						fid:func.id
					}));
					obj.parent().children("#newFunction").val('');
					addFuncEvent();
				}
			});
		}
		
		function deleteFunc(obj){
			if(!confirm("确定删除!")){
				return;
			}
			
			var delFunc = $.ajax({
				url : "/func/delete/"+obj.parent().attr("fid"),
				type : "POST",
				async:false,
				dataType : "json"
			});
			
			delFunc.done(function(data){
				if(data.code == 1){
					obj.parent().remove();
					obj.parent().next().remove();
				}else{
					alert(data.msg);
				}
			});
		}
		
		
		$(document).ready(function(){
			loadProject();
			$("#parseUrl").click(function(){
				parse();
			});	
		});
	</script>
</body>
